package com.hevery.security.core.validate.code;

import com.hevery.security.core.properties.SecurityConstants;
import com.hevery.security.core.properties.SecurityProperties;
import com.hevery.security.core.validate.code.image.ImageCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author: zhy
 * @description: 继承OncePerRequestFilter过滤器保证每次只能被调用一次；
 * 实现接口InitializingBean是Spring初始化bean的一种方式，在Spring初始化ValidateCodeFilter的时候会自动调用重写的afterPropertiesSet的方法。
 * @date: created on 2017/10/26
 * @modified by:
 */
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean{

//    private AuthenticationFailureHandler authenticationFailureHandler;
//
//    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
//
//    /**用来存储当前拦截的url*/
//    private Set<String> urls = new HashSet<>();
//
//    private SecurityProperties securityProperties;
//
//    private AntPathMatcher pathMatcher = new AntPathMatcher();
//
//
//    @Override
//    public void afterPropertiesSet() throws ServletException {
//        super.afterPropertiesSet();
//        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getImage().getUrl(), ",");
//        if(configUrls != null){
//            for (String configUrl : configUrls) {
//                urls.add(configUrl);
//            }
//        }
//        //登录请求也必须进行验证码校验
//        urls.add("/authentication/form");
//    }
//
//    /**
//     * 对验证码进行校验，如果成功则执行下一个UsernamePasswordAuthenticationFilter过滤器；如果失败则调用自定义错误处理器AuthenticationFailureHandler返回错误信息
//     * @param request
//     * @param response
//     * @param filterChain
//     * @throws ServletException
//     * @throws IOException
//     */
//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//
//        boolean action = false;
//        //比如说urls={"/user","/user/*"}，而request.getRequestURI()是user/1，按道理应该对请求中的url进行验证码的校验
//        //所以这个时候通过equals进行判断是不可取的，所以我们可以通过Spring中的一个工具类AntPathMatcher来进行正则匹配的判断。
//        for (String url : urls){
//            if(pathMatcher.match(url, request.getRequestURI())){
//                action = true;
//            }
//        }
//        //如果是登录请求，并且请求的方法是post则进行处理
////        if(StringUtils.equals("/authentication/form", request.getRequestURI()) && StringUtils.equalsIgnoreCase(request.getMethod(), "post")){
//          if(action){
//            try {
//                validate(new ServletWebRequest(request));
//            }catch (ValidateCodeException e){
//                //如果捕获到异常，则用之前自定义的错误处理器来处理异常发霉JSON格式的信息或者跳转页面；注意：失败处理完之后一定要直接返回，不能执行下面的doFilter方法
//                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
//                return;
//            }
//        }
//        filterChain.doFilter(request,response);
//    }
//
//    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
//
//        //获取Session中存入的验证码的值
//        ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX + "IMAGE");
//
//        //获取请求中传来的验证码的值
//        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");
//
//        if(StringUtils.isBlank(codeInRequest)){
//            throw new ValidateCodeException("验证码的值不能为空");
//        }
//        if(codeInSession == null){
//            throw new ValidateCodeException("验证码不存在");
//        }
//
//        //如果已经过期，将当前验证码从Session中移除掉
//        if(codeInSession.isExpired()){
//            sessionStrategy.removeAttribute(request,ValidateCodeProcessor.SESSION_KEY_PREFIX + "IMAGE");
//            throw new ValidateCodeException("验证码已过期");
//        }
//        if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)){
//            throw new ValidateCodeException("验证码不匹配");
//        }
//        //验证码验证成功，将已经验证成功的验证码从Session中移出
//        sessionStrategy.removeAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX + "IMAGE");
//    }
//
//    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
//        return authenticationFailureHandler;
//    }
//
//    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
//        this.authenticationFailureHandler = authenticationFailureHandler;
//    }
//
//    public SessionStrategy getSessionStrategy() {
//        return sessionStrategy;
//    }
//
//    public void setSessionStrategy(SessionStrategy sessionStrategy) {
//        this.sessionStrategy = sessionStrategy;
//    }
//
//    public SecurityProperties getSecurityProperties() {
//        return securityProperties;
//    }
//
//    public void setSecurityProperties(SecurityProperties securityProperties) {
//        this.securityProperties = securityProperties;
//    }

    /**
     * 验证码校验失败处理器
     */
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;


    /**
     * 系统配置信息
     */
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 系统中的验证码处理器
     */
    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    /**
     * 存放所有需要校验验证码的url
     */
    private Map<String, ValidateCodeType> urlMap = new HashMap<>();

    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {

        super.afterPropertiesSet();

        urlMap.put(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM, ValidateCodeType.IMAGE);
        addUrlToMap(securityProperties.getCode().getImage().getUrl(), ValidateCodeType.IMAGE);
        
        urlMap.put(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, ValidateCodeType.SMS);
        addUrlToMap(securityProperties.getCode().getSms().getUrl(), ValidateCodeType.SMS);
    }

    protected void addUrlToMap(String urlString, ValidateCodeType type) {
        if (StringUtils.isNotBlank(urlString)) {
            String[] urls = StringUtils.splitByWholeSeparatorPreserveAllTokens(urlString, ",");
            for (String url : urls) {
                urlMap.put(url, type);
            }
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        ValidateCodeType type = getValidateCodeType(request);
        if (type != null) {
            logger.info("校验请求(" + request.getRequestURI() + ")中的验证码,验证码类型" + type);
            try {
                validateCodeProcessorHolder.findValidateCodeProcessor(type)
                        .validate(new ServletWebRequest(request, response));
                logger.info("验证码校验通过");
            } catch (ValidateCodeException exception) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
                return;
            }
        }

        chain.doFilter(request, response);
    }

    /**
     * 获取校验码的类型，如果当前请求不需要校验，则返回null
     *
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(HttpServletRequest request) {
        ValidateCodeType result = null;
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}
